/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * WallpaperInternalFrame.java
 *
 * Created on 22.06.2010, 09:37:23
 */
package GUI.iFrames;

import input.HEATMAP_BUFFER_IO;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.imageio.ImageIO;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;

import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.PaintScale;
import org.jfree.chart.renderer.xy.XYBlockRenderer;
import org.jfree.data.xy.DefaultXYZDataset;

import toolz.IMS_CSV_File;
import DATA.iDataSetParts.Measurement;
import DATA.iDataSetParts.SubstanceInfo;
import GUI.BaseFrame;
import GUI.WaitJDialog;
import GUI.ChartTools.WBRG_PaintScale;
import GUI.iFrames.DataSourceComponents.DataSourcesInternalFrame;

/**
 * 
 * @author Bunkowski
 */
public class WallpaperInternalFrame extends javax.swing.JInternalFrame {

	public static final long serialVersionUID = 1L;

// TODO Remove unused code found by UCDetector
// 	int cellWidth = 250;

	/** Creates new form WallpaperInternalFrame */
	public WallpaperInternalFrame() {
		initComponents();
	}

	public WallpaperInternalFrame(DataSourcesInternalFrame dif) {
		initComponents();
		try {
			init(dif);
		} catch (IOException ex) {
		}
	}

	private void init(final DataSourcesInternalFrame dif) throws IOException {

		final WallpaperInternalFrame wif = this;

		final Vector<Measurement> measurements = dif.idataset.measurements;
		final Vector<SubstanceInfo> areas = dif.idataset.substanceInfos;

		final HashMap<String, Measurement> mhm = new HashMap<String, Measurement>();

		for (int i = 0; i < measurements.size(); i++) {
			mhm.put(measurements.get(i).measurementID, measurements.get(i));
		}

		final WaitJDialog wait = new WaitJDialog("Wait", dif.table.getSelectedRowCount(), dif);
		Runnable runnable = new Runnable() {

			public void run() {

				// header
				JPanel header = new JPanel();
				header.setBackground(Color.red);
				header.setLayout(new BoxLayout(header, BoxLayout.X_AXIS));

				center.add(header);

				int column1size = 0;
				int columnSize = 0;

				int[] selectedRowsArray = dif.table.getSelectedRows();
				int nrOfSelectedRows = selectedRowsArray.length;
				Vector<Integer> selectedRows = new Vector<Integer>(nrOfSelectedRows);
				for (int i = 0; i < nrOfSelectedRows; i++) {
					selectedRows.add(selectedRowsArray[i]);
				}

				for (int i = 0; i < dif.table.getRowCount(); i++) {
					if (selectedRows.contains(i)) {
						Measurement measurement = mhm.get(dif.table.getValueAt(i, 1));
						double rtFactor;
						String noAlignmentFound = "";
						if (dif.idataset.peaklists.containsKey(measurement.measurementID)) {
							rtFactor = dif.idataset.peaklists.get(measurement.measurementID).getRtFactor();
						} else {
							rtFactor = 1;
							noAlignmentFound = " Warning NO ALIGNMENT";
						}
						System.out.println("alignfactor:" + rtFactor);
						wait.tick(i, measurement.filename + noAlignmentFound);

						Vector wrap = HEATMAP_BUFFER_IO.loadFromCache(measurement);

						if (wrap.size() == 0) {
							IMS_CSV_File ims_file = new IMS_CSV_File(new File(measurement.path));
							wrap = HEATMAP_BUFFER_IO.loadFromFile(ims_file, false);
						} else {
							System.out.println("Using cache object for wallpaper");
						}

						double[][] jfcmap = (double[][]) wrap.get(0);
						double[] scaleK0 = (double[]) wrap.get(2);
						double[] scaleRT = (double[]) wrap.get(3);

						double[][] alignedJFCmap = new double[jfcmap.length][jfcmap[0].length];

						for (int k = 0; k < jfcmap[0].length; k++) {
							alignedJFCmap[0][k] = jfcmap[0][k];
							alignedJFCmap[1][k] = (jfcmap[1][k] * rtFactor);
							alignedJFCmap[2][k] = jfcmap[2][k];
						}

						DefaultXYZDataset imsdds = new DefaultXYZDataset();
						imsdds.addSeries("noname", alignedJFCmap);

						double amplify = 40;
						if (dif.heatmapInternalFrame != null) {
							amplify = dif.heatmapInternalFrame.getAmplify();
						}
						PaintScale ps = new WBRG_PaintScale(0, amplify);

						XYBlockRenderer xybr = new XYBlockRenderer();
						xybr.setPaintScale(ps);
						xybr.setDataBoundsIncludesVisibleSeriesOnly(true);
						xybr.setBlockWidth((float) scaleK0[scaleK0.length - 1] / (float) scaleK0.length);
						xybr.setBlockHeight(rtFactor * ((float) scaleRT[scaleRT.length - 1] / (float) scaleRT.length));

						System.out.println("Creating plot");
						NumberAxis RTaxis = new NumberAxis("RT");
						NumberAxis K0axis = new NumberAxis("1/k0");
						K0axis.setAutoTickUnitSelection(true);

						XYPlot heatmapPlot = new XYPlot(imsdds, K0axis, RTaxis, xybr);
						JFreeChart chart = new JFreeChart(heatmapPlot);
						chart.removeLegend();
						chart.setBackgroundPaint(Color.white);

						JPanel row = new JPanel();
						row.setBackground(Color.white);
						row.setLayout(new BoxLayout(row, BoxLayout.X_AXIS));

						String measurementClass = "";
						if (!dif.getClassforMeasurement(measurement).equals("")) {
							measurementClass = "CLASS: " + dif.getClassforMeasurement(measurement);
						}

						String idLabel = "";
						if (dif.selectedLabel != -1) {
							idLabel += "  " + dif.idataset.getHeader().get(dif.selectedLabel);
							idLabel += ": ";
							idLabel += dif.table.getValueAt(i, dif.selectedLabel);
							idLabel += "<br>";
						}

						JLabel measurementHead = new JLabel("<HTML>" + measurement.filename + "<br>" + idLabel
								+ measurementClass + "</HTML>");
						measurementHead.setMaximumSize(measurementHead.getPreferredSize());
						measurementHead.setAlignmentY(1);
						row.add(measurementHead);
						column1size = measurementHead.getPreferredSize().width;

						for (int j = 0; j < areas.size(); j++) {
							SubstanceInfo area = areas.elementAt(j);
							ChartRenderingInfo info = new ChartRenderingInfo();

							if (!(new File("tmp").exists())) {
								new File("tmp").mkdir();
							}
							File f = new File("tmp/" + area.name + " in " + measurement.filename + ".jpg");

							heatmapPlot.getDomainAxis().setLowerBound(area.dt - area.dtTolerance);
							heatmapPlot.getDomainAxis().setUpperBound(area.dt + area.dtTolerance);

							heatmapPlot.getRangeAxis().setLowerBound(area.rt - area.rtTolerance);
							heatmapPlot.getRangeAxis().setUpperBound(area.rt + area.rtTolerance);
							try {
								// BufferedImage bi = new BufferedImage(200, 200, BufferedImage.TYPE_INT_RGB);
								// ChartPanel cp = new ChartPanel(chart);
								// cp.setSize(200, 200);
								// cp.paint(bi.getGraphics());
								ChartUtilities.saveChartAsPNG(f, chart, 200, 200, info);
							} catch (IOException ex) {
								Logger.getLogger(WallpaperInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
							}
							ImageIcon imageIcon = new ImageIcon(f.getPath());

							// ImageIcon imageIcon = new ImageIcon(bi);
							JLabel label = new JLabel(imageIcon);
							label.setBackground(Color.white);
							row.add(label);
							columnSize = label.getPreferredSize().width;
							f.delete();
						}
						center.add(row);

					}
				}

				ImageIcon i1 = textIcon("Measurement", column1size, 40, Color.white);
				JLabel nameheader = new JLabel(i1);
				header.add(nameheader);

				for (int j = 0; j < areas.size(); j++) {
					SubstanceInfo area = areas.elementAt(j);
					ImageIcon ii = textIcon(area.name, columnSize, 40, Color.white);
					JLabel label = new JLabel(ii);
					header.add(label);
				}
				// }

				BaseFrame.applyFrame(wif);
				wif.setLocation(wif.getLocation());
				wif.moveToFront();
				wif.show();
				wait.dispose();
			}
		};
		Thread thread = new Thread(runnable);
		wait.setThread(thread);
		thread.start();

	}

	private ImageIcon textIcon(String text, int width, int height, Color color) {
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		for (int x = 0; x < bi.getWidth(); x++) {
			for (int y = 0; y < bi.getHeight(); y++) {
				bi.setRGB(x, y, color.getRGB());
			}
		}
		Graphics g = bi.getGraphics();
		g.setColor(Color.BLACK);
		g.drawString(text, 3, height / 2);
		g.drawRect(0, 0, width - 1, height - 1);
		return new ImageIcon(bi);
	}

	/**
	 * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The
	 * content of this method is always regenerated by the Form Editor.
	 */
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		center = new javax.swing.JPanel();
		jMenuBar1 = new javax.swing.JMenuBar();
		jMenu1 = new javax.swing.JMenu();
		jMenuItem1 = new javax.swing.JMenuItem();
		jMenu2 = new javax.swing.JMenu();

		setClosable(true);
		setMaximizable(true);
		setResizable(true);
		setTitle("Wallpaper");

		center.setBackground(new java.awt.Color(255, 255, 255));
		center.setLayout(new javax.swing.BoxLayout(center, javax.swing.BoxLayout.Y_AXIS));
		jScrollPane1.setViewportView(center);

		jMenu1.setText("File");

		jMenuItem1.setText("Save as image");
		jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jMenuItem1ActionPerformed(evt);
			}
		});
		jMenu1.add(jMenuItem1);

		jMenuBar1.add(jMenu1);

		jMenu2.setText("Edit");
		jMenuBar1.add(jMenu2);

		setJMenuBar(jMenuBar1);

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
				jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 404,
				Short.MAX_VALUE));
		layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(
				jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 278,
				Short.MAX_VALUE));

		pack();
	}// </editor-fold>//GEN-END:initComponents

	private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jMenuItem1ActionPerformed
		JFileChooser chooser = new JFileChooser(BaseFrame.getSelectedFileTreeFile());
		chooser.setDialogType(JFileChooser.SAVE_DIALOG);
		int returnVal = chooser.showOpenDialog(this);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			if (!file.toString().endsWith(".png")) {
				file = new File(file.getPath() + ".png");
			}
			BufferedImage img = new BufferedImage(center.getWidth(), center.getHeight(), BufferedImage.TYPE_INT_RGB);
			center.paint(img.createGraphics());
			try {
				ImageIO.write(img, "png", file);
			} catch (IOException ex) {
			}
		}
	}// GEN-LAST:event_jMenuItem1ActionPerformed
		// Variables declaration - do not modify//GEN-BEGIN:variables

	private javax.swing.JPanel center;
	private javax.swing.JMenu jMenu1;
	private javax.swing.JMenu jMenu2;
	private javax.swing.JMenuBar jMenuBar1;
	private javax.swing.JMenuItem jMenuItem1;
	private javax.swing.JScrollPane jScrollPane1;
	// End of variables declaration//GEN-END:variables
}
